package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.MonitoringRecAdapter1;
import com.mingtu.jgspatrol.bean.MonitoringRecZdPeople;
import com.mingtu.jgspatrol.databinding.FragmentMonitoringRecRecordBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.jgspatrol.utils.MySPTools;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MonitoringRecFragment1 extends BaseBindingFragment<FragmentMonitoringRecRecordBinding> implements LazyFragmentPagerAdapter.Laziable {
    
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private int position;
    private static final String ARG_PARAM = "param";
    private MonitoringRecAdapter1 monitoringRecAdapter;

    public static MonitoringRecFragment1 getInstance(int position) {
        MonitoringRecFragment1 ef = new MonitoringRecFragment1();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_PARAM, position);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            position = getArguments().getInt(ARG_PARAM);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_monitoring_rec_record;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());
        //添加自定义分割线
//        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_dive_line));
//        binding.recycler.addItemDecoration(divider);


        monitoringRecAdapter = new MonitoringRecAdapter1(context);

        if(isOpenLoadAnimation){
            monitoringRecAdapter.isFirstOnly(isFirstOnly);
            monitoringRecAdapter.openLoadAnimation(animationType);
        }
        monitoringRecAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(monitoringRecAdapter);
        monitoringRecAdapter.setOnItemClickListener(new  BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MonitoringRecZdPeople.DataBean.ListBean.SnapInfoBean snapInfoBean = monitoringRecAdapter.getData().get(position).getSnapInfo();
                String url = snapInfoBean.getSnapUrl();
                ArrayList<LocalMedia> pictureMediaList = new ArrayList<>();
                LocalMedia localMedia =  LocalMedia.generateHttpAsLocalMedia(url);
                pictureMediaList.add(localMedia);
                BaseApplication.initPreviewModel().startActivityPreview(0, false, pictureMediaList);
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getRecRecord(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getRecRecord(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(monitoringRecAdapter.getData(), Constant.PAGE_SIZE);
                    getRecRecord(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 获取视频识别记录列表
     *
     * @param pageNum
     */
    private void getRecRecord(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }

        String beginTime = SPStaticUtils.getString(MySPTools.monitoringRecFliteBeginTime);
        String endTime = SPStaticUtils.getString(MySPTools.monitoringRecFliteEndTime);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
//        hashMap.put("code", code);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_CAMERA_MATTER_PEOPLE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                MonitoringRecZdPeople monitoringRecZdPeople = new MonitoringRecZdPeople();
                                monitoringRecZdPeople = gson.fromJson(result, MonitoringRecZdPeople.class);
                                List<MonitoringRecZdPeople.DataBean.ListBean> dataBeans = monitoringRecZdPeople.getData().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;

                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            monitoringRecAdapter.replaceData(dataBeans);
                                        } else {
                                            monitoringRecAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }
                        }

                    }
                });
    }

    /**
     * 重置数据
     */
    public void refreshData() {
        getRecRecord(1);
    }
}